import request from '@/utils/request'

const OSS = require("ali-oss");

let client;

export function getStsToken() {
  return request({
    url: '/oss/getStsToken',
    method: 'get'
  })
}

// 在客户端使用临时访问凭证初始化OSS客户端，用于临时授权访问OSS资源。
export const uploadFile = async (dir, fileName, filePath) => {
  // 设置客户端请求访问凭证的地址。
  client = await getOssClient();
  client.put(dir + fileName, filePath).then((res) => {
    console.log(res)
  }).catch(e => console.log(e))
};

async function getOssClient() {
  try {
    const data = await getStsToken();
    client = new OSS({
      // yourRegion填写Bucket所在地域。以华东1（杭州）为例，yourRegion填写为oss-cn-hangzhou。
      region: 'oss-cn-beijing',
      accessKeyId: data.data.accessKeyId,
      accessKeySecret: data.data.accessKeySecret,
      stsToken: data.data.securityToken,
      // 填写Bucket名称。
      bucket: "ikf-static",
    });
    return client;
  } catch (error) {
    console.log(error);
  }
}

export async function partUpload(file, dir, progressCallback) {
  try {
    let options = {
      // 获取分片上传进度、断点和返回值。
      progress: progressCallback,
      // 设置并发上传的分片数量。
      parallel: 8,
      // 设置分片大小。默认值为1 MB，最小值为100 KB。
      partSize: 1024 * 1024 * 20,
      mime: file.type
    }
    client = await getOssClient();
    const {
      res: resp
    } = await client.multipartUpload(dir + file.name, file, options)
    return resp.requestUrls
  } catch (e) {
    console.log(e);
  }
}


/**
 * 断点续传
 * @param {Object} client oss客户端
 * @param {Object} file 上传的文件
 * @param {Object} dir  oss上传的文件夹
 * @param {Object} progressCallback 分片回调进度
 * @param {Object} checkPoint  断点
 */
export async function resumeUpload(file, dir, progressCallback, checkPoint) {
  try {
    let options = {
      // 获取分片上传进度、断点和返回值。
      progress: progressCallback,
      // 断点
      checkpoint: checkPoint,
    }
    client = await getOssClient();
    const {
      res: resp
    } = await client.multipartUpload(dir + file.name, file, options)
    return resp.requestUrls
  } catch (e) {
    console.log(e);
  }

}

/**
 * 结束上传并删除碎片
 * @param {Object} uploadId
 * @param {Object} name
 */
export function abortUpload(uploadId, name) {
  client.abortMultipartUpload(name, uploadId);
}

export function cancel() {
  client.cancel();
}


